<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Contact extends UserBackEndController {
	public function __construct()
	{
		parent::__construct();
		$this->load->library('mypaging');
	}

	private function intialPaging()
	{
		$this->mypaging->setCount($this->contact_model->countContact($this->user_id));
		$this->mypaging->setLimit(CONTACT_LIMIT);
        $folder = $this->role == ROLE_ADMIN ? ADMIN_FOLDER : SHOP_FOLDER;
		$this->mypaging->setMainURL(contact_paging_url($folder));
		$this->mypaging->setSuffix($this->config->item('url_suffix'));
	}

	public function index($pageIndex = 1)
	{
		$this->intialPaging();
		$pagingBar = $this->mypaging->getBar($pageIndex);
		$offset = ($pageIndex - 1) * CONTACT_LIMIT;
		$aContact = $this->contact_model->paging($this->user_id, CONTACT_LIMIT, $offset);
		$aReturn = array(
			'pageTitle' => 'Liên hệ',
			'aContact'  => $aContact,
			'pagingBar' => $pagingBar,
            'aJS'       => assets('js/contact.js', false, 'admin')
        );
		$this->renderView('backend/user/contact/index', $aReturn);
	}

	public function get($id){
		$contact = $this->contact_model->get($id);
		if($contact==null){
			show_404();
		}
		$aReturn = array('contact' => $contact);
		$this->load->view('backend/user/contact/single.html.php', $aReturn);
	}

	public function changeStatus(){
		$date = get_current_date();
		$aResult = array();
		$contact = $this->input->post('contact');
		$id = $this->encrypt->decode($contact['id']);
		if($id===false){
			$aResult = array(
				'code' => 0,
				'title' => $this->lang->line('system_error'),
				'text' => $this->lang->line('update_fail'));
		} else {
			//set unread status
			$aInfo = array();
            if(isset($contact['unread'])){
				if($contact['unread']==1){
					$aInfo['unread'] = 1;
				} else {
					$aInfo['unread'] = 0;
				}
				$aInfo['updated_at'] = $date;
			}

			//set deleted status
			if(isset($contact['delete_flg'])){
				if($contact['delete_flg']==1){
					$aInfo['deleted_at'] = $date;
				} else {
					$aInfo['deleted_at'] = NULL;
					$aInfo['updated_at'] = $date;
				}
			}
			$result = $this->contact_model->changeStatus($id, $aInfo);
			if(!$result){
				$aResult = array(
					'code' => 0,
					'title' => $this->lang->line('system_error'),
					'text' => $this->lang->line('update_fail'));
			} else {
				$aResult = array(
					'code' => 1,
					'text' => $this->lang->line('update_success'));
			}
		}
		$this->renderJSON($aResult);
	}
}
?>